(function ($) {
    var SETTINGS = {
        READ_JDBC: {title: '表输入', iconCls: 'step-icon-read-jdbc'},
        JSON: {title: 'JSON转换', iconCls: 'step-icon-json'},
        XML: {title: 'XML转换', iconCls: 'step-icon-xml'},
        SCRIPT_SQL: {title: 'SQL脚本', iconCls: 'step-icon-script-sql'},
        WRITE_JDBC: {title: '表输入', iconCls: 'step-icon-write-jdbc'},
        WRITE_SAP: {title: 'SAP输出', iconCls: 'step-icon-sap'},
    };


    $.fn.step = function (method, param) {
        if (typeof method == "string") {
            return $.fn.step.methods[method](this, param);
        }
        param = method || {};
        return this.each(function () {
            //获取step全局参数
            var data = $.data(this, "step");
            if (data) {
                //合并全局和指定参数
                $.extend(data.options, param);
            } else {
                let unitType = param.unitType || 'JSON';
                let options = $.extend({}, $.fn.step.defaults, $.fn.step.parseOptions(this), param);
                if (!options.iconCls) {
                    options.iconCls = SETTINGS[unitType].iconCls;
                }
                if (!options.describe) {
                    options.describe = SETTINGS[unitType].title;
                }
                //初始坐标
                if (!options.left) {
                    options.left = 50;
                }
                if (!options.top) {
                    options.top = 50;
                }
                $.data(this, "step", {options: options});
            }
            create(this);
        });
    };


    function create(e) {
        console.log('create a step.')
        //读取bom绑定的属性
        let options = $.data(e, 'step').options;
        console.log(options)

        let astep = $(e).empty().addClass('design-step')
            .attr("id", options.id || options.stepId)
            .append('<div class="step-icon ' + options.iconCls + '"></div>')
            .append('<div class="step-title">' + options.describe + '</div>')
            .offset({left: options.left, top: options.top})
            .draggable({deltaY:200,
                onEndDrag: function () {
                    let offset = $(this).offset();
                    $.data(this, {x: offset.left, y: offset.top});
                    console.log(offset)
                    if (options.fromStepId || options.toStepId) {
                        astep.step('link');
                    }
                },
            })
            .dblclick(function () {
                let options = $.data(this, "step").options;
                let unit = {
                    id: options.unitType + '_' + options.stepId,
                    stepId: options.stepId,
                    describe: options.describe,
                    unitType: options.unitType
                };
                if ($('#' + unit.id).length) {
                    $('#' + unit.id).units('open');
                } else {
                    $('<div id="' + unit.id + '"></div>').appendTo('#design').units(unit);
                }
            })
        ;
        if (options.fromStepId || options.toStepId) {
            astep.step('link');
        }
    }


    function linkStep(from, to) {
        console.log(from, to)
        if (typeof from == "string") {
            if (from.indexOf(':') > -1) {
                from = from.replace(':', '_')
            }
            from = from.startsWith('#') ? $(from) : $('#' + from);

        }
        if (typeof to == "string") {
            if (to.indexOf(':') > -1) {
                to = to.replace(':', '_')
            }
            to = to.startsWith('#') ? $(to) : $('#' + to);
        }

        if (from.length > 0 && to.length > 0) {
            let linkId = from.step('options').id + '__' + to.step('options').id;
            let link = $('#' + linkId);
            //不remove的话,重复设置offset和transform之后会错乱
            link.remove();
            link = $('<div id="' + linkId + '" class="step-line"></div>').appendTo('#design');
            from = from.children('.step-icon');
            to = to.children('.step-icon');
            let fos = from.offset();
            fos = {left: fos.left + 18, top: fos.top + 18};
            let tos = to.offset();
            tos = {left: tos.left + 18, top: tos.top + 18};

            //勾股定理
            let h = fos.top - tos.top;
            let w = fos.left - tos.left;
            //连接线长度
            let length = Math.sqrt(h * h + w * w);
            //连接线 起点坐标 top 取两点水平中间左侧坐标, left取坐标小者+图表宽度
            let start = {top: (fos.top + tos.top) / 2, left: (fos.left + tos.left) / 2 - length / 2};
            //旋转角度
            let rad = Math.atan2((tos.top - fos.top), (tos.left - fos.left));
            //连接线旋转弧度/角度
            let transform = 'rotate(' + rad + 'rad)';
            //设置连接线
            link.empty().width(length).removeAttr('css').offset(start).css('transform', transform);
        } else {
            console.log('do not link');
        }
    }

    $.fn.step.defaults = {
        id: null,
        iconCls: null,
        stepId: null,
        stepType:null,
        stepName:null,
        stepTitle:null,
        width:60,
        height:60,
        left:null,
        top:null,
        fromStepId: null,
        toStepId: null,
    };

    $.fn.step.methods = {
        options: function (jq) {
            return $.data(jq[0], "step").options;
        }, getData: function (jq) {
            let options = $.data(jq[0], "step").options;
            return options.data;
        }, link: function (jq) {
            let options = jq.step('options');
            let fromStepId = options.fromStepId;
            let stepId = options.stepId;
            let toStepId = options.toStepId;
            if (fromStepId) {
                linkStep(fromStepId, stepId);
            }
            if (toStepId) {
                linkStep(stepId, toStepId);
            }
        }, fromStep: function (jq, from, to) {

        }, toStep: function (jq, from, to) {

        }
    };
    $.fn.step.parseOptions = function (selector) {
        var options = $.extend(
            {},
            $.parser.parseOptions(
                selector,
                [
                    "id", "left", "top", "iconCls",
                    "stepId", "convertId", "describe", "unitType", "fromStepId", "toStepId"
                ]
            )
        );
        return options;
    };

    function getData(options, colunms) {
        let data = {};
        $.each(colunms, function (i, item) {
            data[item] = options[item];
        });
        return data;
    }


    // $.fn.stepline=function(_arg1,_arg2){
    //
    // };
    // $.fn.stepline.defaults = {
    //     id: null,
    //     from: {},
    //     to: {},
    //     cls:null,
    //
    // }
})(jQuery);
